function GetProducts(p) {
	$("div#productContent div.loading").css("width", $("div#productContent").width());
	$("div#productContent div.loading").css("height", $("div#productContent").height());
	$("div#productContent div.loading").css("display", "block");
	$.ajax({
		url:"../ajax/ajax.GetProduct_Backend.php?page="+p,
		type: "GET",
		dataType: "html",
		cache: false,
		success: function (data) {
			$("div#productContent").html(data);
			$("ul.pager > li > a").click(function () {
				GetProducts($(this).attr("page"));
            });
            ProductManager.OnDetailClick();
            ProductManager.OnDelete();
			$("div#productContent div.loading").css("display", "none");
		}
	});
}

var ProductManager = {
    InitDialog: function(){
        $('#dialog').dialog({
    	    autoOpen: false,
    	    width: 800,
            height:500,
    	    buttons: {
    		    "Chỉnh sửa": function() { 
    			    $(this).dialog("close");
                    
                    code = $(this).find("#productCode").attr("code");
                    window.location.href="EditProduct.php?code="+code;
                    
    		    }    
    	    }
        });
    },
    
    OnDetailClick: function() {
        $("a.detail").click(function(){
            $("div#productContent div.loading").css("width", $("div#productContent").width());
            $("div#productContent div.loading").css("height", $("div#productContent").height());
            $("div#productContent div.loading").css("display", "block");
            $.ajax({
                url: "../ajax/ajax.dialog_ProductDetail.php?code=" + $(this).attr('code'),
                type: "GET",
                cache: false,
                dataType: "html",
                success: function (data) {
                    $("#dialog").html(data);
                    $("#dialog").dialog('open');
                    $("div#productContent div.loading").css("display", "none");
                }
            });
        });
    },
    
    OnDelete: function(){
        $("a.deleteProduct").click(function(){
            if (confirm("Bạn có chắc muốn xóa sản phẩm: " + $(this).attr("code") + " ?") == true){
                $("div#productContent div.loading").css("width", $("div#productContent").width());
                $("div#productContent div.loading").css("height", $("div#productContent").height());
                $("div#productContent div.loading").css("display", "block");
                var temp = $(this).parent().parent();
                $.ajax({
                    url: "../ajax/ajax.DeleteProduct.php?",
                    type: "POST",
                    data: {"code" : $(this).attr("code")},
                    cache: false,
                    dataType: "html",
                    success: function (data) {
                        if(data=="1")
                        {
                            temp.fadeOut('slow');
                        }
                        else
                        {
                            alert("Xảy ra lỗi khi xóa sản phẩm, vui lòng thử lại");
                        }
                        $("div#productContent div.loading").css("display", "none");
                    }
                });
            }
        });
    },
    
    init: function(){
        ProductManager.InitDialog();
        ProductManager.OnDetailClick();
        ProductManager.OnDelete();
        $("ul.pager > li > a").click(function () {
			GetProducts($(this).attr("page"));
        });
    }
} 

var CreateProduct = {
	OnNameChange: function () {
		$(":text#Name").keyup(function () {
			var nameLocDau = locdau($(this).val());
			$(":text#Code").val(nameLocDau);
		});
	},
    
    OnSectionChange: function () {
		$("#SectionID").change(function () {
            $.ajax({
                url: "../ajax/ajax.CategoryDDL.php",
                type: "POST",
                data: {"sectionID": $(this).val()},
                cache: false,
                dataType: "html",
                success: function (data) {
                    $("#CategoryID").html(data);
                }
            });
		});
	},

	btnAddFileClick: function () {
        $("#btnAddFile").click(function(){
            $("div#fileContain").append("<div class='clear'></div><input type='file' name='image[]' />");
        });	
	},

	validate: function () {
		$("#frmProduct").validate({
			rules: {
				Name: "required",
				Price: "positiveNumber"
			},

			messages: {
				Name: "Vui lòng nhập tên sản phẩm",
				Price: "Giá tiền phải là số nguyên và lớn hơn 0"
			}
		});
	},

	init: function () {
		CreateProduct.OnNameChange();
        CreateProduct.OnSectionChange();
        $.validator.addMethod('positiveNumber',
            function(value) {
                return Number(value) > 0;
            }, 'Enter a positive number.');
        CreateProduct.validate();
        CreateProduct.btnAddFileClick();
        $.ajax({
                url: "../ajax/ajax.CategoryDDL.php",
                type: "POST",
                data: {"sectionID": $("#SectionID").val()},
                cache: false,
                dataType: "html",
                success: function (data) {
                    $("#CategoryID").html(data);
                }
        });
	}
}

var EditProduct = {    
    OnSectionChange: function () {
		$("#SectionID").change(function () {
            $.ajax({
                url: "../ajax/ajax.CategoryDDL.php",
                type: "POST",
                data: {"sectionID": $(this).val()},
                cache: false,
                dataType: "html",
                success: function (data) {
                    $("#CategoryID").html(data);
                }
            });
		});
	},
    
    LoadSection_Category: function(section, category){
        $("#SectionID").val(section);
        $.ajax({
            url: "../ajax/ajax.CategoryDDL.php",
            type: "POST",
            data: {"sectionID": section},
            cache: false,
            dataType: "html",
            success: function (data) {
                $("#CategoryID").html(data);
                $("#CategoryID").val(category);
                EditProduct.OnSectionChange();
            }
        });
    },
    
    LoadColor: function(color){
        var arrColor = color.split('|');
        for(i = 0; i < arrColor.length; i++){
            $("#crosscolor-" + arrColor[i]).css("display", "block");
            $("#cbcolor-" + arrColor[i]).attr("checked", "checked");
        }  
        $("input:text[name='Color']").val(color);
    },

	btnAddFileClick: function () {
        $("#btnAddFile").click(function(){
            $("div#fileContain").append("<div class='clear'></div><input type='file' name='image[]' />");
        });	
	},

	validate: function () {
		$("#frmProduct").validate({
			rules: {
				Name: "required",
				Price: "positiveNumber"
			},

			messages: {
				Name: "Vui lòng nhập tên sản phẩm",
				Price: "Giá tiền phải là số nguyên và lớn hơn 0"
			}
		});
	},
        
    OnDeleteImage: function(){
        $("a.delImage").click(function(){
            $(this).parent().parent().fadeOut('slow');
            if($.trim($(":text[name='ImageSrcDeleted']").val()).length == 0)
                $(":text[name='ImageSrcDeleted']").val($(this).attr("imgSrc"));
            else
                $(":text[name='ImageSrcDeleted']").val($(":text[name='ImageSrcDeleted']").val() + "|" + $(this).attr("imgSrc"));
        }); 
    },

	init: function () {
        $.validator.addMethod('positiveNumber',
            function(value) {
                return Number(value) > 0;
            }, 'Enter a positive number.');
        EditProduct.validate();
        EditProduct.btnAddFileClick();
        EditProduct.OnDeleteImage();
        $.ajax({
                url: "../ajax/ajax.CategoryDDL.php",
                type: "POST",
                data: {"sectionID": $("#SectionID").val()},
                cache: false,
                dataType: "html",
                success: function (data) {
                    $("#CategoryID").html(data);
                }
        });
	}
}

function locdau(str) {
	str = str.replace(/à|á|ạ|ả|ã|â|ầ|ấ|ậ|ẩ|ẫ|ă|ằ|ắ|ặ|ẳ|ẵ/g, "a");
	str = str.replace(/À|Á|Ạ|Ả|Ã|Â|Ầ|Ấ|Ậ|Ẩ|Ẫ|Ă|Ằ|Ắ|Ặ|Ẳ|Ẵ/g, "A");
	str = str.replace(/è|é|ẹ|ẻ|ẽ|ê|ề|ế|ệ|ể|ễ/g, "e");
	str = str.replace(/È|É|Ẹ|Ẻ|Ẽ|Ê|Ề|Ế|Ệ|Ể|Ễ/g, "E");
	str = str.replace(/ì|í|ị|ỉ|ĩ/g, "i");
	str = str.replace(/Ì|Í|Ị|Ỉ|Ĩ/g, "I");
	str = str.replace(/ò|ó|ọ|ỏ|õ|ô|ồ|ố|ộ|ổ|ỗ|ơ|ờ|ớ|ợ|ở|ỡ/g, "o");
	str = str.replace(/Ò|Ó|Ọ|Ỏ|Õ|Ô|Ồ|Ố|Ộ|Ổ|Ỗ|Ơ|Ờ|Ớ|Ợ|Ở|Ỡ/g, "O");
	str = str.replace(/ù|ú|ụ|ủ|ũ|ư|ừ|ứ|ự|ử|ữ/g, "u");
	str = str.replace(/Ù|Ú|Ụ|Ủ|Ũ|Ư|Ừ|Ứ|Ự|Ử|Ữ/g, "U");
	str = str.replace(/ỳ|ý|ỵ|ỷ|ỹ/g, "y");
	str = str.replace(/Ỳ|Ý|Ỵ|Ỷ|Ỹ/g, "Y");
	str = str.replace(/đ/g, "d");
	str = str.replace(/Đ/g, "D");
	str = str.replace(/!|@|%|\^|\*|\(|\)|\+|\=|\<|\>|\?|\/|,|\.|\:|\;|\'| |\"|\&|\#|\[|\]|~|$|_/g, "-");
	str = str.replace(/-+-/g, "-");
	str = str.replace(/^\-+|\-+$/g, "");
	return str;
}

function OnClickColor(id) {
	if (document.getElementById('cb' + id).checked == false) {
		document.getElementById('cb' + id).checked = true
		document.getElementById('cross' + id).style.display = 'block';
	}
	else {
		document.getElementById('cb' + id).checked = false;
		document.getElementById('cross' + id).style.display = 'none';
	}
    colors = "";
    $("div#colorBarContain :checked").each(function (index, term) {
    	if (index == 0)
    		colors += $(term).val();
    	else
    		colors += "|" + $(term).val();
    });
    $("input:text[name='Color']").val(colors);
}